package com.lagou.edu.controller;

import com.lagou.edu.dao.ResumeDao;
import com.lagou.edu.pojo.Resume;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class ResumeController {

    @Autowired
    private ResumeDao resumeDao;

//    //初步测试框架合并，mvc controller执行queryall
//    //并测试异常捕获
//    @RequestMapping("/queryAll")
//    @ResponseBody
//    public List<Resume> queryAll() throws Exception {
//        int test = 1/0;
//        return resumeDao.findAll();
//    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String home(){
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletResponse response, HttpSession session,RedirectAttributes redirectAttributes, String username, String password){
        //仅支持admin用户登录
        if ("admin".equals(username) && "admin".equals(password)){
            session.setAttribute("SESSION_USER_NAME",username);
            response.addHeader("SESSION_USER_NAME",username);
            return "redirect:list";
        }
        //登录失败返回登录页
        redirectAttributes.addFlashAttribute("msg","账号或密码错误");
        return "redirect:login";
    }

    @RequestMapping("/list")
    public ModelAndView queryAll(){
        List<Resume> all = resumeDao.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("list",all);
        modelAndView.setViewName("list");
        return modelAndView;
    }

    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Object addOrUpdate(@RequestBody  Resume resume,RedirectAttributes redirectAttributes){
        resumeDao.save(resume);
        Map<String, String > map = new HashMap<>();
        map.put("status", "ok");
        return map;
    }

    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.GET)
    public ModelAndView addOrUpdate(@RequestParam(value = "id", required = false) Long id){
        ModelAndView modelAndView = new ModelAndView();
        if (id != null){
            Resume resume = resumeDao.findById(id).get();
            modelAndView.addObject("resume",resume);
            modelAndView.setViewName("addOrUpdate");
        }
        return modelAndView;
    }


    @RequestMapping("/deleteOne")
    public String deleteOne(@RequestParam("id") Long id){
        resumeDao.deleteById(id);
        return "redirect:list";
    }


}
